<?php
/**     
  *
  * Copyright (c) 2009, Persistent Systems Limited
  *
  * Redistribution and use, with or without modification, are permitted 
  *  provided that the following  conditions are met:
  *   - Redistributions of source code must retain the above copyright notice, 
  *     this list of conditions and the following disclaimer.
  *   - Neither the name of Persistent Systems Limited nor the names of its contributors 
  *     may be used to endorse or promote products derived from this software 
  *     without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */

/**
 * Home Page Model 
 */
require_once 'model/homePageModel.php';
/**
 * HomePage_Controller class to display graph of company sales data with provided filter on different options
 * @access public
 */
class HomePage_Controller
{
	/** 
     * Class constructor
	 * @access public
	 */
	public function __construct(){ }
	/**
	 * This function display Home Page
	 * @access public
	 */
	public function showHomePage()
	{
		$regionId = 0;
		$productId = 0;
		$fromYear = date('Y');
		$toYear = date('Y');
		$year = date('Y');
		$yearRdo = "";
		$monthRdo = "Checked";
		$regionList = array();
		$productList = array();
		$validateFormFields = array();
		$aggregatedSales = array();
		$errors = array();
		$result = array();
		$months = array('1'=>'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec');
		$isApplicationLevelError = false;
			
		try{
			$homePageModelObj = new HomePageModel();
			//Get Region List
			$regionData = $homePageModelObj->getRegionList();
			if (isset($regionData['error'])){
				$errors[] = $regionData['error'];
			}
			if(isset($regionData['result'])){
				$regionList = $regionData['result'];
			}
			//Get Product List
			$productData = $homePageModelObj->getProductList();
			if (isset($productData['error'])){
				$errors[] = $productData['error'];
			} 
			if(isset($productData['result'])){
				$productList = $productData['result'];
			}

			// empty session data of graph
			unset($_SESSION["graphInput"]);

			if(empty($errors)){
				if($_POST){
					if ($_POST['rdoGroupFilter'] == 'year'){
						$yearRdo = "Checked";
						$monthRdo = "";	
					} else {
						$monthRdo = "Checked";
					}
					
					$validateFormFieldsErrors = $homePageModelObj->validateFormFields($_POST);
					
					foreach($validateFormFieldsErrors as $error){
						$errors[] = $error;
					}
					
					if(empty($errors)){
						$regionId = $_POST['lstregion'];
						$productId =$_POST['lstProduct'];
						$fromYear = $_POST['listFromYear'];
						$toYear = $_POST['listToYear'];
						$year = $_POST['listYear'];
						$result = $this->showConsolidateDataByGraph($_POST);
						if(isset($result['error'])){
							$errors = $result['error'];
							$isApplicationLevelError = true;
						}
					} else {
						$isApplicationLevelError = true;
					}
					
				} else {
					$monthlyData = array('Jan'=>0,'Feb'=>0,'Mar'=>0,'Apr'=>0,
										 'May'=>0,'Jun'=>0,'Jul'=>0,'Aug'=>0,
										 'Sept'=>0,'Oct'=>0,'Nov'=>0,'Dec'=>0);
					$aggregatedSalesData = $homePageModelObj->getConsolidatedSalesData();
					if (isset($aggregatedSalesData['error'])){
						$errors[] = $aggregatedSalesData['error'];
					}
					if(isset($aggregatedSalesData['result'])){
						$aggregatedSales = $aggregatedSalesData['result'];
					}

					if(empty($errors)){
						//Execute following loop if there is data found
						if(count($aggregatedSales) > 0){
							foreach($monthlyData as $key => $value){
								foreach($aggregatedSales as $annualSale){
									if($annualSale['Month'] == $key){
										$monthlyData[$key] = $annualSale['Quantity'];
									}
								}
							}
						}
						$_SESSION['graphInput']  = array('title'=> 'Company Sales Data','y-label'=>'Quantity','x-label'=>'Monthly data [Year - '.date("Y").']','data'=>$monthlyData);
					} else {
						$isApplicationLevelError = true;
					}
				}
			} else {
				$isApplicationLevelError = true;
			}
			

		} catch (Exception $e){
			throw ($e);
		}
		if(!$isApplicationLevelError){
			include_once('view/home.php');
		} else {
			include_once('view/error.php');
		}
	}

	/**
	 * This function graph of consolidated sales data with either Monthly or Yearly option
	 * @access public
	 * @param array $postFieldData Array of form fields used for filter option for graph
	 * @return array $result Result contains array of consolidated sales data or errors if any received from web service
	 */
	public function showConsolidateDataByGraph($postFieldData)
	{
		$regionId = 0;
		$productId = 0;
		$fromYear = date('Y');
		$toYear = date('Y');
		$year = date('Y');
		$yearRdo = "";
		$monthRdo = "Checked";
		$regionList = array();
		$productList = array();
		$validateFormFields = array();
		$aggregatedSales = array();
		$errors = array();
		$result = array();
		try{
			$regionId = $postFieldData['lstregion'];
			$productId = $postFieldData['lstProduct'];
			if ($_POST['rdoGroupFilter'] == 'year'){
				$yearRdo = "Checked";
				$monthRdo = "";
				$fromYear = $postFieldData['listFromYear'];
				$toYear = $postFieldData['listToYear'];
				$isYearlyOrMonthly = 'yearly';
				
			}
			if ($_POST['rdoGroupFilter'] == 'month'){
				$monthRdo = "Checked";
				$yearRdo = "";
				$year = $postFieldData['listYear'];
				$isYearlyOrMonthly = 'monthly';
			}

			$homePageModelObj = new HomePageModel();
			$aggregatedSalesData = $homePageModelObj->getConsolidatedSalesData($productId, $regionId, $year, $fromYear, $toYear, $isYearlyOrMonthly);
			if (isset($aggregatedSalesData['error'])){
				$errors[] = $aggregatedSalesData['error'];
			}
			if(isset($aggregatedSalesData['result'])){
				$aggregatedSales = $aggregatedSalesData['result'];
			}
			if(empty($errors)){
				if ($_POST['rdoGroupFilter'] == 'year'){
					if(count($aggregatedSales) > 0){
						foreach($aggregatedSales as $annualSale){
							for($year = $fromYear; $year<=$toYear; $year++){
								if($annualSale['Year'] == $year){
									$data[$year] = $annualSale['Quantity'];
								} else {
									if(!isset($data[$year])){$data[$year] = 0;}
								}
							}
						}
					} else {
						for($year = $fromYear; $year<=$toYear; $year++){
							$data[$year] = 0;
						}
					}
					$_SESSION['graphInput']  = array('title'=> 'Company Sales Data','y-label'=>'Quantity','x-label'=>'Year("'.$fromYear.'" - "'.$toYear.'")','data'=>$data);

				//Else loop for Monthly data
				} else {
					$monthlyData = array('Jan'=>0,'Feb'=>0,'Mar'=>0,'Apr'=>0,
										 'May'=>0,'Jun'=>0,'Jul'=>0,'Aug'=>0,
										 'Sept'=>0,'Oct'=>0,'Nov'=>0,'Dec'=>0);
					if(count($aggregatedSales) > 0){
						foreach($monthlyData as $key => $value){
							foreach($aggregatedSales as $monthlySales){
								if($monthlySales['Month'] == $key){
									$monthlyData[$key] = $monthlySales['Quantity'];
								}
							}
						}
					}
					$_SESSION['graphInput']  = array('title'=> 'Company Sales Data','y-label'=>'Quantity','x-label'=>'Monthly data [Year - '.$year.']','data'=>$monthlyData);
				}
			}
			if(empty($errors)){
				$result['result'] =true;
			} else {
				$result['error'] = $errors;
			}
		
		} catch(Exception $e){
			throw ($e);
		}
		return $result;
	}
}
$homePage = new HomePage_Controller();
?>